let express = require("express");
let userRouter = express.Router();
let jwt = require("jsonwebtoken");
let config = require("../config");
var md5 = require("md5-node");
const { SuccessModel, ErrorModel } = require("../utils/resModule");
const { UserModel } = require("../model/index");

// 用户注册接口 添加用户
userRouter.post("/user/register", async function (req, res) {
  await UserModel.create({ ...req.body,password: md5(req.body.password)});
  res.json(new SuccessModel("注册成功"));
});

// 添加用户
userRouter.post("/user/account", async function (req, res) {
  if(!req.body.avatar)req.body.avatar = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1060453240,1808119494&fm=26&gp=0.jpg'
  await UserModel.insertMany({ ...req.body,password: md5(req.body.password)});
  res.json(new SuccessModel("添加成功"));
});

// 登录接口
userRouter.post("/user/login", async function (req, res) {
  let { username, password } = req.body;
  let query = { username, password};
  try {
    let result = await UserModel.findOne(query);
    let resultJSON = result.toJSON();
    let token = jwt.sign(resultJSON, config.Secret);
    res.json(new SuccessModel({ token }));
  } catch (error) {
    res.json(new ErrorModel("登录失败"));
  }
});

// 查询当前用户信息接口
userRouter.get("/currentUser", async function (req, res) {
  let authorization = req.headers["authorization"];
  console.log(authorization, "authorization>>>");
  let token = authorization.split(" ")[1];
  let result = jwt.verify(token, config.Secret, { expiresIn: config.EXPIRESD });
  result.name = result.username
  res.json(result);
});

// 查询所有用户信息
userRouter.get("/user/account", async function (req, res) {
  let {current=1,pageSize=10,sorter,filter={},...query} = req.query;
  if(sorter){
    sorter = sorter ? JSON.parse(sorter) : {};
    for (const key in sorter) {
        sorter[key] = sorter[key] === 'ascend' ? 1 : -1;
    }
  }
  if(filter){
    filter = filter? JSON.parse(filter) : {};
    for (const key in filter) {
      if(filter[key]){
        query[key] = filter[key]
      }
   }
  }
  let total = await UserModel.countDocuments(query);
  let users = await UserModel.find(query).sort(sorter).skip((current-1)*pageSize).limit(Number(pageSize));
  let dataSource = users.map(item=>item.toJSON());
  const result = {
    data: dataSource,
    total,
    success:true,
    pageSize,
    current,
  }
  return res.json(result)
});

// 删除用户信息
userRouter.delete("/user/account", async function (req, res) {
  let hasRes = await UserModel.findOne(req.body);
  if (hasRes) {
    let { deletedCount } = await UserModel.remove(req.body);
    if (deletedCount) {
      res.json(new SuccessModel("删除成功"));
    }
  } else {
    res.json(new ErrorModel("删除失败"));
  }
});

// 修改用户信息
userRouter.put("/user/account", async function (req, res) {
  let { nModified } = await UserModel.update(
    req.query,
    { $set: { ...req.body, password: md5(req.body.password) } },
    { multi: true }
  );
  if (nModified) {
    res.json(new SuccessModel("修改成功"));
  } else {
    res.json(new ErrorModel("修改失败"));
  }
});

// 退出登录
userRouter.get("/login/outLogin", async function (req, res) {
  console.log('layoooo')
  res.json({
    data: {},
    success: true,
  });
});

module.exports = {
  userRouter,
};
